package com.yhy.wxzn.wcs.wcsWmsCommunication;


import com.alibaba.fastjson.JSON;
import com.yhy.wxzn.common.utils.HttpClientSpring;
import com.yhy.wxzn.common.utils.WcsUtils;
import com.yhy.wxzn.wcs.entity.WcsTask;
import com.yhy.wxzn.wcs.enums.TaskStatus;
import com.yhy.wxzn.wcs.service.impl.WcsTaskServiceImpl;
import com.yhy.wxzn.wcs.wcsWmsCommunication.bean.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ThreadPoolExecutor;


@Slf4j
@Component
public class ToWmsImpl  implements ToWms{


    @Value("${wms.ipPort}")
    private String ipPort;


    @Resource
    private ThreadPoolExecutor threadPool;

    @Autowired
    private WcsTaskServiceImpl taskService;

    /**
     * 入库任务申请
     * @param taskApply
     * @return
     */
    @Override
    public WmsResponses exeTaskApply(TaskApply taskApply) {
        log.info("入库任务申请=>{}", JSON.toJSONString(taskApply));
        String result = "";
        for (int i = 0; i < 3; i++) {
            try {
                result = HttpClientSpring.sendPostRequest(ipPort + "/fromwcs/inware-task",JSON.toJSONString(taskApply));

                log.info("入库任务申请第{}次申请,返回值:{}",i+1, result);
                if (StringUtils.isNotBlank(result))  break;
            } catch (Exception e) {
                log.error("入库任务申请 接口异常：{}", e.getMessage(), e);
                WcsUtils.sleep(1000);
            }
        }

        try {
            if (StringUtils.isBlank(result))  return WmsResponses.returnError("多次请求，未成功收到wms响应值");
            WmsResponses wmsResponses = JSON.parseObject(result, WmsResponses.class);

            if (wmsResponses == null || wmsResponses.getReturnStatus() == null || wmsResponses.getReturnInfo() == null) return  WmsResponses.returnError("响应值无法转为对象");
            return  wmsResponses;
        } catch (Exception e) {
            log.error("入库任务申请，任务申请接口解析返回值出现异常！{}", e.getMessage(), e);
            return WmsResponses.returnError("入库任务申请，任务申请接口解析返回值出现异常");
        }
    }

    @Override
    public WmsResponses emptyPalletApply(PalletRequest palletRequest) {
        return null;
    }

    /**
     * 任务状态上报
     * @param taskStatusRtn
     */
    @Override
    public void executionPhase(TaskStatusRtn taskStatusRtn) {
        Runnable runnable = () -> {
            log.info("任务状态上报,申请=>{}", JSON.toJSONString(taskStatusRtn));
            String result = "";
            for (int i = 0; i < 3; i++) {
                try {
                    result = HttpClientSpring.sendPostRequest(ipPort + "/fromwcs/task",JSON.toJSONString(taskStatusRtn));

                    log.info("任务状态上报,第{}次申请,返回值:{}",i+1, result);
                    if (StringUtils.isNotBlank(result))  break;
                } catch (Exception e) {
                    log.error("任务状态上报 接口异常：{}", e.getMessage(), e);
                    WcsUtils.sleep(1000);
                }
            }


            if (StringUtils.isBlank(result)) {
                log.error("任务状态上报,多次请求，未成功收到wms响应值");
                return;
            }

            try {
                WmsResponses wmsResponses = JSON.parseObject(result, WmsResponses.class);
                Integer returnStatus = wmsResponses.getReturnStatus();
                Date msgTime = wmsResponses.getMsgTime();
                String returnInfoFromWms = wmsResponses.getReturnInfo();
                if (returnStatus == WcsProperties.SUCCESS) {
                    log.info("任务状态上报,任务编号:" + taskStatusRtn.getTaskId() + " 任务状态：" + taskStatusRtn.getTaskStatus()
                            + " 的任务上报成功！ 时间-->" + msgTime);
                    if (taskStatusRtn.getTaskStatus() == TaskStatus.FINISH.getTaskProgress()){
                        WcsTask task = new WcsTask();
                        task.setWmsTaskId(taskStatusRtn.getTaskId());
                        taskService.updateTaskStatusByWmsId(task,TaskStatus.COMMITTED);
                    }
                } else if (returnStatus == WcsProperties.FAIL) {
                    log.error("任务状态上报,任务编号:" + taskStatusRtn.getTaskId() + " 任务状态：" + taskStatusRtn.getTaskStatus()
                            + " 的任务上报失败！原因-->" + returnInfoFromWms + " 时间-->"
                            + msgTime);
                } else {
                    log.error("任务状态上报,returnStatus状态码不存在！");
                }
            } catch (Exception e) {
                log.error("任务状态上报,任务执行状态上报接口解析返回值出现异常！{}", e.getMessage(), e);
            }

        };


        threadPool.execute(runnable);
    }

    @Override
    public WmsResponses deviceStatus(List<ReturnMsgDevice> deviceErrRtn) {
        return null;
    }


}
